package controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.portlet.PortletRequest;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import net.sf.json.JSONObject;
import net.sf.json.util.JSONTokener;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.portlet.bind.annotation.RenderMapping;

import util.Constants;
import util.SearchCommand;
import domain.Movies;

@Controller
@RequestMapping("VIEW")
public class SearchMovieController {
	
	private String movieName;
	private String optionalYear;
	private Movies movie;
	
	 @ModelAttribute("searchCommand")
	  protected SearchCommand getSearchCommand(PortletRequest request) throws Exception {
	    SearchCommand command = new SearchCommand() ;
	    return command;
	  }
	 
	 @RenderMapping(params = "action=searchMovie")
	  protected ModelAndView handleRender(@ModelAttribute(value="searchCommand")SearchCommand command,
	      RenderRequest request, 
	      RenderResponse response) 
	      throws Exception {
	    
	    SearchCommand searchCommand = command;
	    this.movieName = searchCommand.getTitle();
	    this.optionalYear = searchCommand.getYear();
	    movie = new Movies();
	    this.Search();
	    Map<String, Object> model = new HashMap<String, Object>();
	    model.put("movie", this.movie);
	    return new ModelAndView("searchResult", model);
	  }
	
	public void Search() throws IOException{
		String url = Constants.URL_IMDB_SEARCH;
		if (optionalYear ==null || optionalYear.equals("")){
			url += URLEncoder.encode(movieName,"UTF-8");
		}else{
			url += URLEncoder.encode(movieName,"UTF-8") + "&year=" + URLEncoder.encode(optionalYear,"UTF-8");
		}
		URL serverAddress = new URL(url);
		HttpURLConnection connection = (HttpURLConnection)serverAddress.openConnection();
		InputStream is = connection.getInputStream();
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		String read;
		while ((read = reader.readLine()) != null) {
			String json = read;
			JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
			if (object.containsKey("error")){
				this.movie.setTitle("Not Found");
			}else{
				this.movie.setTitle((object.containsKey("title")) ? object.getString("title") : "" );
				this.movie.setLinkToIMDB((object.containsKey("imdburl")) ? URLDecoder.decode(object.getString("imdburl"),"UTF-8") : "" );
				this.movie.setCountry((object.containsKey("country")) ? object.getString("country") : "" );
				this.movie.setLanguages((object.containsKey("languages")) ? niceLink(object.getString("languages")): "" );
				this.movie.setGenre((object.containsKey("genres")) ? object.getString("genres") : "" );
				this.movie.setRating((object.containsKey("rating")) ? object.getString("rating") : "" );
				this.movie.setNumberofVotes((object.containsKey("votes")) ? object.getString("votes") : "" );
				this.movie.setYear((object.containsKey("year")) ? object.getString("year") : "" );
				
			}
		}
		reader.close();
	}
	
	public String niceLink(String str){
	while(str.indexOf("&nbsp;") > -1){
		str = str.replaceAll("&nbsp;", "");
	}
	return str;
}
}
